package com.wx.qrcode.wx.util;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.wx.qrcode.common.ResultEnum;
import com.wx.qrcode.common.constant.RedisConstant;
import com.wx.qrcode.common.constant.WxConstant;
import com.wx.qrcode.common.constant.WxUrlConstant;
import com.wx.qrcode.common.dto.WxCreateQrCodeDTO;
import com.wx.qrcode.common.dto.WxCreateQrCodeResultDTO;
import com.wx.qrcode.common.redis.RedisService;
import com.wx.qrcode.common.util.SpringContextUtils;
import com.wx.qrcode.wx.properties.WxProperties;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

/**
 * @author yz
 * @description
 * @date 2022-03-23 11:23
 */
@Slf4j
public class WxUtil {
    private static WxProperties properties;
    private static RedisService redisService;

    static {
        properties = SpringContextUtils.getBeanByClass(WxProperties.class);
        redisService = SpringContextUtils.getBeanByClass(RedisService.class);
    }

    /**
     * description 获取Access token
     *
     * @return java.lang.String
     * @Author yz
     * @Date 13:38 2022/3/23
     **/
    public static String getAccessToken() {
        try {
            Object o = redisService.get(RedisConstant.ACCESS_TOKEN);
            if (!Objects.isNull(o)) {
                return String.valueOf(o);
            }
            String result = HttpUtil.get(StrUtil.format(WxUrlConstant.ACCESS_TOKEN_URL, properties.getAppID(), properties.getAppsecret()));
            String token = JSONUtil.parseObj(result).getStr(WxConstant.ACCESS_TOKEN);
            Assert.notNull(token, ResultEnum.ACCESS_TOKEN_IS_EMPTY.getMsg());
            Long expires = JSONUtil.parseObj(result).getLong(WxConstant.EXPIRES_IN);
            redisService.set(RedisConstant.ACCESS_TOKEN, token, expires);
            return token;
        } catch (Exception e) {
            log.error("获取Access_token失败", e);
            return null;
        }
    }

    /**
     * description 生成临时二维码 字符串模式
     *
     * @param signature
     * @return void
     * @Author yz
     * @Date 15:42 2022/3/23
     * @Param
     **/
    public static WxCreateQrCodeResultDTO createQrCode(String signature) {
        try {
            String accessToken = getAccessToken();
            WxCreateQrCodeDTO build = new WxCreateQrCodeDTO(Dict.create().set(WxCreateQrCodeDTO.SCENE_STR, signature));
            String result = HttpRequest.post(StrUtil.format(WxUrlConstant.CREATE_QR_CODE, accessToken)).body(JSONUtil.toJsonStr(build)).execute().body();
            return JSONUtil.toBean(result, WxCreateQrCodeResultDTO.class);
        } catch (Exception e) {
            log.error("生成临时二维码失败", e);
            return null;
        }
    }


    
}
